package com.wang.transfer.util.algorithm;

/**
 * 将两个字符串形式的非负整数相加，并返回字符串
 * 不适用内置的大整数
 */
public class AddStrings {

    public static void main(String[] args) {
        String num1 = "9", num2 = "99";
//        System.out.println(new AddStrings().addStrings(num1, num2));
        System.out.println(new AddStrings().addStrings2(num1, num2));
    }

    public String addStrings(String num1, String num2) {
        int len = Math.min(num1.length(), num2.length());
        int t = 0, x = num1.length() - 1, y = num2.length() - 1;
        StringBuilder str = new StringBuilder();
        for (int i = len - 1; i >= 0; i--) {
            int sum = Integer.parseInt(String.valueOf(num1.charAt(x--))) + Integer.parseInt(String.valueOf(num2.charAt(y--))) + t;
            str.insert(0, sum % 10);
            t = sum / 10;
        }
        if (num1.length() != num2.length()) {
            String num = num1.length() == len ? num2 : num1;
            int l = num.length() - len;
            while (t != 0 && l > 0) {
                int sum = Integer.parseInt(String.valueOf(num.charAt(l-- - 1))) + t;
                str.insert(0, sum % 10);
                t = sum / 10;
            }
            if (l >= 0) {
                str.insert(0, num.substring(0, l));
            }
        }
        if (t != 0) {
            str.insert(0, t);
        }
        return str.toString();
    }

    public String addStrings2(String num1, String num2) {
        int i = num1.length() - 1, j = num2.length() - 1, add = 0;
        StringBuilder ans = new StringBuilder();
        while(i >= 0 || j >= 0 || add != 0) {
            int x = i >= 0 ? num1.charAt(i--) - '0' : 0;
            int y = j >= 0 ? num2.charAt(j--) - '0' : 0;
            int result = x + y + add;
            ans.append(result % 10);
            add = result / 10;
        }
        ans.reverse();
        return ans.toString();
    }
}
